<?php
/**
 * ==========================================================================
 * @revision    $Id: ag_google_analytics.php 7 2011-07-24 00:03:12Z agbiggora@gmail.com $
 * @package		Joomla
 * @since       {SINCE}
 * @subpackage  AG_Google_Analytics
 * @version     {PROJECTVERSION}
 * @copyright	Copyright Alexey Gordeyev IK © 2010-2011 - All rights reserved.
 * @license		GPLv2
 * @author		Alexey Gordeyev IK
 * @author mail	aleksej@gordejev.lv
 * @website		http://www.gordejev.lv
 * ==========================================================================
 */

/* no direct access */
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

/**
 * Google Analytics and Webmaster Verify System Plugin
 * @package	AG Google Analytics
 * @since   1.0.8
 */
class plgSystemAG_google_analytics extends JPlugin {
	/**
	 * Constructor
	 *
	 * For php4 compatability we must not use the __constructor as a constructor for plugins
	 * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
	 * This causes problems with cross-referencing necessary for the observer design pattern.
	 *
	 * @access	protected
	 * @param	object $subject The object to observe
	 * @param   array  $params
	 * @return  void
	 */
	function plgSystemAG_google_analytics(& $subject, $params) {
		parent::__construct($subject, $params);
	}

	/**
	 * Do something onAfterInitialise
	 * @since    1.0.8
	 * @access   public
	 * @return   void
	 */
	function onAfterInitialise(){

		$mainframe =& JFactory::getApplication();
		// Get Plugin params
		$pluginparams = $this->params;
		// get document
		$document	=& JFactory::getDocument();
		// Load user
		$user =& JFactory::getUser();
		// get data
		$insert_methode  = $pluginparams->get( 'insert_methode' );
		$ag_resource     = $pluginparams->get( 'ag_resource' );
		$ag_var_ip       = $pluginparams->get( 'ag_var_ip' );
		$ag_var_us       = $pluginparams->get( 'ag_var_us' );
		$ag_custom_var   = $pluginparams->get( 'ag_custom_var' );
		$backend         = $pluginparams->get( 'backend' );
		$ag_track        = $pluginparams->get( 'ag_track' );
		$google_content  = $pluginparams->get( 'google_key' );
		$yahoo_content   = $pluginparams->get( 'yahoo_key' );
		$bing_content    = $pluginparams->get( 'bing_key' );
		$alexa_content   = $pluginparams->get( 'alexa_key' );
		$yandex_content  = $pluginparams->get( 'yandex_key' );
		$custom_name     = $pluginparams->get( 'custom_name' );
		$custom_content  = $pluginparams->get( 'custom_key' );

		// set meta
		if(!empty($google_content)) { $document->setMetaData("google-site-verification", $google_content); }
		if(!empty($yahoo_content))  { $document->setMetaData("y_key", $yahoo_content); }
		if(!empty($bing_content))   { $document->setMetaData("msvalidate.01", $bing_content); }
		if(!empty($alexa_content))  { $document->setMetaData("alexaVerifyID", $alexa_content); }
		if(!empty($yandex_content)) { $document->setMetaData("yandex-verification", $yandex_content); }
		if(!empty($custom_content)) { $document->setMetaData($custom_name, $custom_content); }

		$REMOTE_ADDR = null;
		if(isset($_SERVER['REMOTE_ADDR'])) { $REMOTE_ADDR = $_SERVER['REMOTE_ADDR']; }
		elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $REMOTE_ADDR = $_SERVER['HTTP_X_FORWARDED_FOR']; }
		elseif(isset($_SERVER['HTTP_CLIENT_IP'])) { $REMOTE_ADDR = $_SERVER['HTTP_CLIENT_IP']; }
		elseif(isset($_SERVER['HTTP_VIA'])) { $REMOTE_ADDR = $_SERVER['HTTP_VIA']; }
		else { $REMOTE_ADDR = 'unknown'; }

		if($insert_methode == 0) {
			$track = false;
			if($backend == 1) { $track = true; }
			else {
				if(!$mainframe->isAdmin()) {
					$track = true;
				}
				else { $track = false; }
			}
	  $raw = array('raw','pdf','ajax');
	  $format = JRequest::getVar('format','','STRING');
	  $no_html = JRequest::getVar('no_html', 0, 'INT');
	  if(in_array($format, $raw) || $no_html == 1 || $format != '') {  $track = false; }

	  if($track == true) {
	  	if(!empty($ag_resource)) {
	  		if($ag_track == 0) {
	  			$tracker_code  = "<script type=\"text/javascript\">\n";
	  			$tracker_code .= "/* BEGIN AG Google Analytics Plugin v.1.0.8 */\n";
	  			$tracker_code .= 'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); ';
	  			$tracker_code .= 'document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));';
	  			$tracker_code .= "\n </script> \n <script type=\"text/javascript\">\n";
	  			$tracker_code .= ' try { var pageTracker = _gat._getTracker("'.$ag_resource.'"); ';
	  			if($ag_var_ip == 1) { $tracker_code .= ' pageTracker._setCustomVar( 1, "user_ip", "'.$REMOTE_ADDR.'", 1 ); '; }
	  			if (!$user->guest) {
	  				if($ag_var_us == 1) { $tracker_code .= ' pageTracker._setCustomVar( 2, "joomla_user", "'.$user->name.'", 1 ); '; }
	  			}
	  			if(!empty($ag_custom_var)) { $tracker_code .= ' '.$ag_custom_var.' '; }
	  			$tracker_code .= " pageTracker._trackPageview(); \n";
	  			$tracker_code .= " } catch(err) {} \n";
	  			$tracker_code .= "/* END AG Google Analytics Plugin v.1.0.8 */\n";
	  			$tracker_code .= "/* ========== www.gordejev.lv =========== */\n";
	  			$tracker_code .= "</script>\n";

	  		}
	  		else {
	  			if(!empty($ag_resource)) {
	  				$tracker_code = "<script type=\"text/javascript\">\n";
	  				$tracker_code .= "/* BEGIN AG Google Analytics Plugin v.1.0.8 */\n";
	  				$tracker_code .= "var _gaq = _gaq || []; \n _gaq.push(['_setAccount', '".$ag_resource."']); \n";
	  				if($ag_var_ip == 1) { $tracker_code .= " _gaq.push(['_setCustomVar', 1, 'user_ip', '".$REMOTE_ADDR."', 1]); \n"; }
	  				if (!$user->guest) {
	  					if($ag_var_us == 1) { $tracker_code .= " _gaq.push(['_setCustomVar', 2, 'joomla_user', '".$user->name."', 1]); \n"; }
	  				}
	  				if(!empty($ag_custom_var)) { $tracker_code .= " ".$ag_custom_var." "; }
	  				$tracker_code .= " _gaq.push(['_trackPageview']); \n (function() { \n";
	  				$tracker_code .= "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; \n";
	  				$tracker_code .= "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; \n";
	  				$tracker_code .= "var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); \n
                      })(); \n";
	  				$tracker_code .= "/* END AG Google Analytics Plugin v.1.0.8 */\n";
	  				$tracker_code .= "/* ========== www.gordejev.lv =========== */\n";
	  				$tracker_code .= "</script>\n";

	  			}
	  		}
	  		$document->addCustomTag($tracker_code);
	  	}
	  }
		}

		return true;

	}

	/**
	 * Do something onAfterRender
	 * @since    1.0.8
	 * @access   public
	 * @return   void
	 */
	function onAfterRender()
	{
		$mainframe =& JFactory::getApplication();
		# Load user
		$user =& JFactory::getUser();
		# Initialise Plugin params
		$pluginparams    = $this->params;
		$insert_methode  = $pluginparams->get( 'insert_methode' );
		$ag_resource     = $pluginparams->get( 'ag_resource' );
		$ag_var_ip       = $pluginparams->get( 'ag_var_ip' );
		$ag_var_us       = $pluginparams->get( 'ag_var_us' );
		$ag_custom_var   = $pluginparams->get( 'ag_custom_var' );
		$backend         = $pluginparams->get( 'backend' );
		$ag_track        = $pluginparams->get( 'ag_track' );
        # Initialise remote address
		$REMOTE_ADDR = null;
		if(isset($_SERVER['REMOTE_ADDR'])) { $REMOTE_ADDR = $_SERVER['REMOTE_ADDR']; }
		elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $REMOTE_ADDR = $_SERVER['HTTP_X_FORWARDED_FOR']; }
		elseif(isset($_SERVER['HTTP_CLIENT_IP'])) { $REMOTE_ADDR = $_SERVER['HTTP_CLIENT_IP']; }
		elseif(isset($_SERVER['HTTP_VIA'])) { $REMOTE_ADDR = $_SERVER['HTTP_VIA']; }
		else { $REMOTE_ADDR = 'unknown'; }
        # Check inserting method
		if($insert_methode == 1) {
			$track = false;
			if($backend == 1) { $track = true; }
			else {
				if(!$mainframe->isAdmin()) {
					$track = true;
				}
				else { $track = false; }
			}
            # Check allow or denied track
			if($track == true) {
				if(!empty($ag_resource)) {
                    # Get page body
					$output = JResponse::getBody();
					$pattern = '</head>';

					if($ag_track == 0) {
						$tracker_code  = "script type=\"text/javascript\">\n";
						$tracker_code .= "/* BEGIN AG Google Analytics Plugin v.1.0.8 */\n";
						$tracker_code .= 'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); ';
						$tracker_code .= 'document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));';
						$tracker_code .= "\n </script> \n <script type=\"text/javascript\">\n";
						$tracker_code .= ' try { var pageTracker = _gat._getTracker("'.$ag_resource.'"); ';
						if($ag_var_ip == 1) { $tracker_code .= ' pageTracker._setCustomVar( 1, "user_ip", "'.$REMOTE_ADDR.'", 1 ); '; }
						if (!$user->guest) {
							if($ag_var_us == 1) { $tracker_code .= ' pageTracker._setCustomVar( 2, "joomla_user", "'.$user->name.'", 1 ); '; }
						}
						if(!empty($ag_custom_var)) { $tracker_code .= ' '.$ag_custom_var.' '; }
						$tracker_code .= " pageTracker._trackPageview(); \n";
						$tracker_code .= " } catch(err) {} \n";
						$tracker_code .= "/* END AG Google Analytics Plugin v.1.0.8 */\n";
						$tracker_code .= "/* ========== www.gordejev.lv =========== */\n";
						$tracker_code .= "</script>\n</head";
						$output = str_replace("</HEAD>","</head>",$output);
						$output = preg_replace($pattern, $tracker_code, $output);

					}
					else {
						if(!empty($ag_resource)) {
							$tracker_code = "script type=\"text/javascript\">\n";
							$tracker_code .= "/* BEGIN AG Google Analytics Plugin v.1.0.8 */\n";
							$tracker_code .= "var _gaq = _gaq || []; \n _gaq.push(['_setAccount', '".$ag_resource."']); \n";
							if($ag_var_ip == 1) { $tracker_code .= " _gaq.push(['_setCustomVar', 1, 'user_ip', '".$REMOTE_ADDR."', 1]); \n"; }
							if (!$user->guest) {
								if($ag_var_us == 1) { $tracker_code .= " _gaq.push(['_setCustomVar', 2, 'joomla_user', '".$user->name."', 1]); \n"; }
							}
							if(!empty($ag_custom_var)) { $tracker_code .= " ".$ag_custom_var." "; }
							$tracker_code .= " _gaq.push(['_trackPageview']); \n (function() { \n";
							$tracker_code .= "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; \n";
							$tracker_code .= "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; \n";
							$tracker_code .= "var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); \n
                      })(); \n";
							$tracker_code .= "/* END AG Google Analytics Plugin v.1.0.8 */\n";
							$tracker_code .= "/* ========== www.gordejev.lv =========== */\n";
							$tracker_code .= "</script>\n</head";
							$output = preg_replace($pattern, $tracker_code, $output);

						}
					}
					# Return page body
					JResponse::setBody($output);
				}
			}
		}
	}
}
?>